package com.sjzl.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Component;

import com.opensymphony.xwork2.ActionContext;
import com.sjzl.entity.UploadFile;
import com.sjzl.entity.User;
import com.sjzl.service.UploadFileService;

@Component("uploadFileServiceImpl")
public class UploadFileServiceImpl extends ServiceImpl<UploadFile> implements UploadFileService{

	@Override
	public void create(UploadFile updateFile) {}


	public void upload(File[] upload,String[] uploadFileName,String[] uploadContentType) {
		String realpath = ServletActionContext.getServletContext().getRealPath("/userUploadFile");//获取真实路径
		File file = new File(realpath);
		if(!file.exists()) file.mkdirs();	//如果不存在就创建
		if(upload==null){
			System.out.println("用户没有选择图片");//如果用户没有选择图片，这里进行处理
			
		}else{
			for(int i=0 ;i<upload.length; i++){
				File fileUpload = upload[i];
				Long length =fileUpload.length();//获取文件的大小
				if(length>1024*1024*16){
					System.out.println("用户上传的文件大于16MB！！");
					//如果用户上传的文件太大，这里进行处理
				}else{
					try {
						FileUtils.copyFile(fileUpload, new File(file, uploadFileName[i]));//上传文件到服务器
						String realName = UUID.randomUUID().toString()+ uploadFileName[i].substring(uploadFileName[i].lastIndexOf("."));// 保存的文件名称，使用UUID+后缀进行保存，可以确保重复上传
						String type = uploadContentType[i];// 文件类型
						UploadFile uploadFile = new UploadFile();
						uploadFile.setDateCreated(new Date());	//保存图片上传时间
						User user = (User) ActionContext.getContext().getSession().get("sessionUser");
						uploadFile.setUploadUserAccount(user.getAccount());//保存上传者名称
						uploadFile.setUploadFileType(type);	//保存上传文件的类型
						uploadFile.setUploadFileName(uploadFileName[i]);
						uploadFile.setUploadRealName(realName);
						uploadFile.setServerPath(realpath);
						this.save(uploadFile);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}
		
	}
	public List<UploadFile> loadDownFile(Integer post_id){
		String hql="from UploadFile where post_id="+post_id;
		List<UploadFile> downLoadFiles =this.list(hql);
		return downLoadFiles;
	}

}
